﻿(function () {

    layui.use(["layer", "jquery", "form", "laydate", "tree"], function () {
        var layer = layui.layer;
        var $ = layui.jquery;
        var form = layui.form;
        var laydate = layui.laydate;
        var tree = layui.tree;
        var users = [];

        $(document).ready(function () {
            loadUsers();
            $("#btn-Search").click(onSearchClick);
        });

        function loadUsers() {
            $("#UserList").html("");
            var loadingIndex = layer.msg(addStyle("正在加载 ......"),
                { icon: 16, shade: 0.01, offset: ["25%"], time: false });
            $.ajax("/ShopManage/User/QueryByWhere", {
                method: "POST",
                data: getQueryParam(),
                complete: function (jqXHR, textStatus) {
                    layer.close(loadingIndex);
                },
                success: function (data, textStatus, jqXHR) {
                    if (data.Success == true) {
                        var data2 = data.Data;
                        if ($.isArray(data2)) {
                            handleData(data2);
                        }
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.msg(addStyle("系统错误，请联系管理员！"),
                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                }
            });

            function handleData(data) {
                users = data;
                var html = $("#UserListTable").html();
                var count = 0;
                data.forEach((item, i) => {
                    var html2 = html;
                    html2 = html2.replace("{{Phone}}", item["Phone"]);
                    html2 = html2.replace("{{Name}}", item["Name"]);
                    html2 = html2.replace("{{InvitationCode}}", item["InvitationCode"]);
                    html2 = html2.replace("{{Reference}}", item["Reference"]);
                    html2 = html2.replace("{{ReferenceInvitationCode}}", item["ReferenceInvitationCode"]);
                    html2 = html2.replace("{{CreateTime}}", item["CreateTime"]);
                    html2 = html2.replace("{{State}}", getStateText(item["State"]));
                    html2 = html2.replace(/\{\{UserId\}\}/g, item["Id"]);
                    $("#UserList").append(html2);
                    $(".view-UserAccountInfo:last").click(onViewUserAccountInfoClick);
                    $(".view-UserStructure:last").click(onViewUserStructureClick);
                    $(".update-UserInfo:last").bind("click", item, onUpdateUserInfoClick);
                    $(".update-UserReference:last").bind("click", item, onUpdateUserReferenceClick);
                    $(".reset-UserState:last").bind("click", item, onResetUserStateClick);
                    $(".reset-ShopManagerLevel:last").bind("click", item, onResetShopManagerLevelClick);
                    $(".reset-UserPassword:last").click(onResetUserPwdClick);
                    count++;
                });
                $("#UserStatistics-Count").text(count);
            }
        }

        function getQueryParam() {
            return {
                Phone: $("#txt-Search-Phone").val(),
                Name: $("#txt-Search-Name").val(),
                InvitationCode: $("#txt-Search-InvitationCode").val(),
                Reference: $("#txt-Search-Reference").val(),
                ReferenceInvitationCode: $("#txt-Search-ReferenceInvitationCode").val(),
                State: $("#sel-Search-State").val()
            }
        }

        function onSearchClick() {
            loadUsers();
        }

        function onViewUserAccountInfoClick() {
            var el = $(this);
            var userId = parseInt(el.attr("tagUserId"), 10);

            layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.5, '#000'],
                skin: 'layui-layer-molv',
                area: ["90%", "80%"],
                offset: "10%",
                resize: false,
                content: '<div Id="ViewUserAccountInfoDlg2">' + $("#ViewUserAccountInfoDlg").html() + '</div>'
            });

            var loadingIndex = layer.msg(addStyle("正在加载 ......"),
                { icon: 16, shade: 0.01, offset: ["25%"], time: false });
            $.ajax("/ShopManage/UserAccount/QueryByUserId", {
                method: "POST",
                data: "UserId=" + userId,
                complete: function (jqXHR, textStatus) {
                    layer.close(loadingIndex);
                },
                success: function (data, textStatus, jqXHR) {
                    if (data.Success == true) {
                        handleData(data.Data);
                    } else {
                        layer.msg(addStyle("加载数据失败: " + data.Msg));
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.msg(addStyle("系统错误，请联系管理员！"),
                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                }
            });

            function handleData(data2) {
                var width = $("#ViewUserAccountInfoDlg2").parent().width();
                var height = $("#ViewUserAccountInfoDlg2").parent().height();
                var height2 = height - 41 - 10 - 10;
                if (data2.WechatCodePath) {
                    var wechatSrc = data2.WechatCodePath;
                    $("#ViewUserAccountInfoDlg2 .wechat")
                        .css("width", width + "px")
                        .css("height", height2 + "px")
                        .attr("src", wechatSrc);
                }
                if (data2.AlipayCodePath) {
                    var alipaySrc = data2.AlipayCodePath;
                    $("#ViewUserAccountInfoDlg2 .alipay")
                        .css("width", width + "px")
                        .css("height", height2 + "px")
                        .attr("src", alipaySrc);
                }
                if (data2.BankAccountName) {
                    $("#ViewUserAccountInfoDlg2 .lbBankAccountName").text(data2.BankAccountName);
                }
                if (data2.Bank) {
                    $("#ViewUserAccountInfoDlg2 .lbBankName").text(data2.Bank);
                }
                if (data2.BankCardNo) {
                    $("#ViewUserAccountInfoDlg2 .lbBankCardNo").text(data2.BankCardNo);
                }
            }
        }

        function onViewUserStructureClick() {
            var el = $(this);
            var userId = parseInt(el.attr("tagUserId"), 10);

            layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.5, '#000'],
                skin: 'layui-layer-molv',
                area: ["90%", "80%"],
                offset: "10%",
                resize: false,
                content: '<div id="ViewUserStructureDlg2">' + $("#ViewUserStructureDlg").html() + '</div>'
            });

            var loadingIndex = layer.msg(addStyle("正在加载 ......"),
                { icon: 16, shade: 0.01, offset: ["25%"], time: false });
            $.ajax("/ShopManage/User/QueryUserStructure", {
                method: "POST",
                data: "UserId=" + userId,
                complete: function (jqXHR, textStatus) {
                    layer.close(loadingIndex);
                },
                success: function (data, textStatus, jqXHR) {
                    if (data.Success == true) {
                        handleData(data.Data);
                    } else {
                        layer.msg(addStyle("加载数据失败: " + data.Msg),
                            { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                        );
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.msg(addStyle("系统错误，请联系管理员！"),
                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                }
            });

            function handleData(data) {
                var treeData = Convert_2_TreeData(data, userId);
                var n = treeData.length;
                var dom = $("#ViewUserStructureDlg2 div").eq(0);
                tree.render({
                    elem: dom,
                    id: "Tree",
                    data: treeData
                });
            }

            function Convert_2_TreeData(arr, rootUserId) {
                var arr2 = arr.filter(item => item["UserId"] == rootUserId);
                if (arr2.length > 0) {
                    var arr3 = [];
                    arr.forEach((item, i) => {
                        var arr4 = arr.filter(item2 => item["InvitationCode"] == item2["ReferenceInvitationCode"]);
                        item["children"] = arr4;
                        arr3.push(item);
                    });

                    var root = arr2[0];
                    var treeArr = [];
                    var treeObj = Convert_2_TreeItemData(root);
                    treeArr.push(treeObj);
                    fun1(treeObj["obj"]["InvitationCode"], treeObj["children"]);
                    return treeArr;
                    function fun1(invitationCode, parent) {
                        var arr4 = arr3.filter(x => x["ReferenceInvitationCode"] == invitationCode);
                        if (arr4.length > 0) {
                            for (var i = 0; i < arr4.length; i++) {
                                var item2 = arr4[i];
                                var treeObj2 = Convert_2_TreeItemData(item2);
                                parent.push(treeObj2);
                                fun1(item2["InvitationCode"], treeObj2["children"]);
                            }
                        }
                    }

                    function Convert_2_TreeItemData(obj) {
                        return {
                            id: obj["UserId"],
                            title: obj["Name"] + " - " + obj["Phone"],
                            obj: obj,
                            children: []
                        };
                    }
                }
                return [];
            }
        }

        function onUpdateUserInfoClick(event) {
            var el = $(this);
            var userId = event.data["Id"];
            var name = event.data["Name"];
            var phone = event.data["Phone"];

            var layerId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.5, '#000'],
                skin: 'layui-layer-molv',
                area: ["80%", "200px"],
                offset: "10%",
                resize: false,
                content: $("#UpdateUserInfoDlg").html(),
                success: function (layero, index, that) {
                    $("#txt-UpdateUserInfoDlg-Name").val(name);
                    $("#txt-UpdateUserInfoDlg-Phone").val(phone);

                    form.verify({
                        name: [/^[a-zA-Z0-9\u4e00-\u9fa5]{2,10}$/, "姓名格式不正确！"]
                    });
                    $("#btn-UpdateUserInfoDlg-OK").bind("click", on_UpdateUserInfoDlg_OKBtn_Click);
                }
            });

            function on_UpdateUserInfoDlg_OKBtn_Click() {
                if (form.validate("#UpdateUserInfoDlg-Form")) {
                    layer.confirm(addStyle("确定要修改会员信息码？")
                        , { icon: 3, title: "满堂创品", offset: "20%" }
                        , function (index) {
                            layer.close(index);

                            var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                                { icon: 16, shade: 0.01, offset: ["25%"], time: false });
                            $.ajax("/ShopManage/User/UpdateUserInfo", {
                                method: "POST",
                                data: {
                                    UserId: userId,
                                    Name: $("#txt-UpdateUserInfoDlg-Name").val(),
                                    Phone: $("#txt-UpdateUserInfoDlg-Phone").val()
                                },
                                complete: function (jqXHR, textStatus) {
                                    layer.close(loadingIndex);
                                },
                                success: function (data, textStatus, jqXHR) {
                                    if (data.Success == true) {
                                        layer.msg(addStyle("更新会员信息成功！"), { time: 1 * 1000 }, function () {
                                            layer.close(layerId);
                                            loadUsers();
                                        });
                                    } else {
                                        layer.msg(addStyle("更新会员信息失败: " + data.Msg),
                                            { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                                        );
                                    }
                                },
                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                    layer.msg(addStyle("系统错误，请联系管理员！"),
                                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                                }
                            });
                        }
                    );
                }
            }
        }

        function onUpdateUserReferenceClick(event) {
            var el = $(this);
            var userId = event.data["Id"];
            var name = event.data["Name"];
            var invitationCode = event.data["InvitationCode"];
            var reference = event.data["Reference"];
            var referenceInvitationCode = event.data["ReferenceInvitationCode"];

            var layerId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.5, '#000'],
                skin: 'layui-layer-molv',
                area: ["80%", "250px"],
                offset: "10%",
                resize: false,
                content: $("#UpdateUserReferenceDlg").html(),
                success: function (layero, index, that) {
                    $("#lb-UpdateUserReferenceDlg-Name").text(name);
                    $("#lb-UpdateUserReferenceDlg-InvitationCode").text(invitationCode);
                    $("#lb-UpdateUserReferenceDlg-Reference").text(reference);
                    $("#lb-UpdateUserReferenceDlg-ReferenceInvitationCode").text(referenceInvitationCode);

                    $("#btn-UpdateUserReferenceDlg-ShowSearchUserDlg").bind("click", { fn: onSearchUserDlgResult }, onUpdateUserReferenceDlgShowSearchUserDlgClick);
                    $("#btn-UpdateUserReferenceDlg-OK").click(onUpdateUserReferenceDlgOKClick);
                }
            });

            function onSearchUserDlgResult(data) {
                reference = data.Name;
                referenceInvitationCode = data.InvitationCode;
                $("#lb-UpdateUserReferenceDlg-Reference").text(reference);
                $("#lb-UpdateUserReferenceDlg-ReferenceInvitationCode").text(referenceInvitationCode);
            }

            function onUpdateUserReferenceDlgShowSearchUserDlgClick(event) {
                var selectedUserData = {
                    Name: "",
                    InvitationCode: ""
                };

                var layerId2 = layer.open({
                    type: 1,
                    title: "满堂创品",
                    shade: [0.5, '#000'],
                    skin: 'layui-layer-molv',
                    area: ["80%", "80%"],
                    offset: "10%",
                    resize: false,
                    content: $("#SearchUserDlg").html(),
                    success: function (layero, index, that) {
                        var html = '';
                        users.forEach(item => {
                            html += '<label tagUserId="' + item["Id"] + '" tagPhone="' + item["Phone"] + '" tagInvitationCode="' + item["InvitationCode"] + '">' + item["Name"] + '</label>';
                        });
                        $("#SearchUserDlg-UserList").append(html);
                        $("#SearchUserDlg-UserList label").click(onUserListLabelClick);
                        $("#btn-SearchUserDlg-Search").click(onSearchUserDlgSearchClick);
                    },
                    btn: ["确 定"],
                    btn1: function (layero, index, that) {
                        if (selectedUserData.Name == "") {
                            layer.msg(addStyle("请先选择会员！"));
                            return;
                        }

                        layer.confirm("确定要选择此会员吗？",
                            { icon: 3, title: "满堂创品", offset: "20%" },
                            function (index2) {
                                layer.close(layerId2);
                                layer.close(index2);

                                if (event.data.fn != null) {
                                    event.data.fn(selectedUserData);
                                }
                            }
                        );
                    }
                });

                function onUserListLabelClick() {
                    var el = $(this);
                    var text = el.text() + " - " + el.attr("tagPhone");
                    $("#lb-SearchUserDlg-Name").text(text);
                    selectedUserData.InvitationCode = el.attr("tagInvitationCode");
                    selectedUserData.Name = el.text();
                }

                function onSearchUserDlgSearchClick() {
                    var val = $("#txt-SearchUserDlg-Name").val();
                    var els = $("#SearchUserDlg-UserList label");
                    for (var i = 0; i < els.length; i++) {
                        var item = els.eq(i);
                        if (item.text().indexOf(val) > -1) {
                            item.show();
                        } else {
                            item.hide();
                        }
                    }
                }
            }

            function onUpdateUserReferenceDlgOKClick() {
                if (name == reference
                    && invitationCode == referenceInvitationCode) {
                    layer.msg(addStyle("推荐人不可以是自己！"));
                    return;
                }

                layer.confirm("确定邀修改会员推荐人吗？",
                    { icon: 3, title: "满堂创品", offset: "20%" },
                    function (index) {
                        layer.close(index);

                        var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                            { icon: 16, shade: 0.01, offset: ["25%"], time: false });
                        $.ajax("/ShopManage/User/UpdateUserReference", {
                            method: "POST",
                            data: {
                                UserId: userId,
                                ReferenceInvitationCode: referenceInvitationCode
                            },
                            complete: function (jqXHR, textStatus) {
                                layer.close(loadingIndex);
                            },
                            success: function (data, textStatus, jqXHR) {
                                if (data.Success == true) {
                                    layer.msg(addStyle("更新会员推荐人成功！"), { time: 1 * 1000 }, function () {
                                        layer.close(layerId);
                                        loadUsers();
                                    });
                                } else {
                                    layer.msg(addStyle("更新会员推荐人失败: " + data.Msg),
                                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                                    );
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                layer.msg(addStyle("系统错误，请联系管理员！"),
                                    { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                            }
                        });
                    }
                );
            }
        }

        function onResetUserStateClick(event) {
            var el = $(this);
            var userId = event.data["Id"];
            var userState = event.data["State"];
            var name = event.data["Name"];

            var layerId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.5, '#000'],
                skin: 'layui-layer-molv',
                area: ["80%", "200px"],
                offset: "10%",
                resize: false,
                success: function (layero, index, that) {
                    //console.log(layero);
                    var el = layero.find(".layui-layer-content").eq(0);
                    el.css("overflow", "visible");
                },
                content: $("#ResetUserStateDlg").html()
            });

            $("#lb-ResetUserStateDlg-Name").text(name);
            $("#sel-ResetUserStateDlg-State").val(userState);
            form.render($("#sel-ResetUserStateDlg-State"));
            $("#btn-ResetUserStateDlg-OK").click(onResetUserStateDlgOKClick);

            function onResetUserStateDlgOKClick() {
                layer.confirm("确定要更新用户状态吗？",
                    { icon: 3, title: "满堂创品", offset: "20%" },
                    function () {
                        var jsonData = {
                            State: $("#sel-ResetUserStateDlg-State").val(),
                            UserId: userId
                        };
                        //console.log(jsonData);

                        var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                            { icon: 16, shade: 0.01, offset: ["25%"], time: false });
                        $.ajax("/ShopManage/User/ResetState", {
                            method: "POST",
                            data: jsonData,
                            complete: function (jqXHR, textStatus) {
                                layer.close(loadingIndex);
                            },
                            success: function (data, textStatus, jqXHR) {
                                if (data.Success == true) {
                                    layer.close(layerId);
                                    layer.msg(addStyle("更新用户状态成功！"), { time: 1 * 1000 }, function () {
                                        loadUsers();
                                    });
                                } else {
                                    layer.msg(addStyle("更新用户状态失败: " + data.Msg));
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                layer.msg(addStyle("系统错误，请联系管理员！"),
                                    { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                            }
                        });
                    }
                );
            }
        }

        function onResetShopManagerLevelClick(event) {
            var el = $(this);
            var userId = event.data["Id"];
            var percent = parseFloat(event.data["ShopManagerLevelPercent"], 10);
            var name = event.data["Name"];

            var layerId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.5, '#000'],
                skin: 'layui-layer-molv',
                area: ["80%", "200px"],
                offset: "10%",
                resize: false,
                success: function (layero, index, that) {
                    //console.log(layero);
                    var el = layero.find(".layui-layer-content").eq(0);
                    el.css("overflow", "visible");
                },
                content: $("#ResetShopManagerLevelDlg").html()
            });

            $("#sel-ResetShopManagerLevelDlg-Level").val(percent);
            form.render($("#sel-ResetShopManagerLevelDlg-Level"));
            $("#lb-ResetShopManagerLevelDlg-Name").text(name);
            $("#btn-ResetShopManagerLevelDlg-OK").click(onResetShopManagerLevelDlgOKClick);

            function onResetShopManagerLevelDlgOKClick() {
                layer.confirm("确定要更新店长级别吗？",
                    { icon: 3, title: "满堂创品", offset: "20%" },
                    function () {
                        var jsonData = {
                            Percent: $("#sel-ResetShopManagerLevelDlg-Level").val(),
                            UserId: userId
                        };
                        //console.log(jsonData);

                        var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                            { icon: 16, shade: 0.01, offset: ["25%"], time: false });
                        $.ajax("/ShopManage/User/ResetShopManagerLevelPercent", {
                            method: "POST",
                            data: jsonData,
                            complete: function (jqXHR, textStatus) {
                                layer.close(loadingIndex);
                            },
                            success: function (data, textStatus, jqXHR) {
                                if (data.Success == true) {
                                    layer.close(layerId);
                                    layer.msg(addStyle("更新店长级别成功！"), { time: 1 * 1000 }, function () {
                                        loadUsers();
                                    });
                                } else {
                                    layer.msg(addStyle("更新店长级别失败: " + data.Msg));
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                layer.msg(addStyle("系统错误，请联系管理员！"),
                                    { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                            }
                        });
                    }
                );
            }
        }

        function onResetUserPwdClick() {
            var el = $(this);
            var userId = parseInt(el.attr("tagUserId"), 10);

            var layerId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.5, '#000'],
                skin: 'layui-layer-molv',
                area: ["90%", "220px"],
                offset: "10%",
                resize: false,
                content: '<div Id="ResetUserPwdDlg2">' + $("#ResetUserPwdDlg").html() + '</div>'
            });

            form.verify({
                pwd: [/\w{6,20}/, "密码格式不正确！"],
                pwd2: function (value, elem) {
                    if ($("#txt-ResetUserPwdDlg-Pwd").val() != $("#txt-ResetUserPwdDlg-Pwd2").val()) {
                        return "两次新密码输入不一致！"
                    }
                    return;
                }
            });

            form.on("submit(filter-ResetUserPwdDlg-OK)", function (data) {
                layer.confirm("确定要重设密码吗？",
                    { icon: 3, title: "满堂创品", offset: "20%" },
                    function () {
                        var jsonData = {
                            Pwd: hex_md5($("#txt-ResetUserPwdDlg-Pwd").val()).toUpperCase(),
                            UserId: userId
                        };
                        //console.log(jsonData);

                        var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                            { icon: 16, shade: 0.01, offset: ["25%"], time: false });
                        $.ajax("/ShopManage/User/ResetPwd", {
                            method: "POST",
                            data: jsonData,
                            complete: function (jqXHR, textStatus) {
                                layer.close(loadingIndex);
                            },
                            success: function (data, textStatus, jqXHR) {
                                if (data.Success == true) {
                                    layer.close(layerId);
                                    layer.msg(addStyle("重设密码成功！"));
                                } else {
                                    layer.msg(addStyle("重设密码失败: " + data.Msg));
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                layer.msg(addStyle("系统错误，请联系管理员！"),
                                    { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                            }
                        });
                    }
                );

                return false;
            });
        }

        function getStateText(state) {
            if (state == 1) {
                return '启用';
            } else if (state == 0) {
                return '<font class="disabledState">禁用</font>';
            }
        }

        function addStyle(str) {
            return '<span style="font-size: 16px;">' + str + '</span>';
        }
    });

})();